package com.platform.qujia.service.impl;

import com.platform.qujia.dao.LabelMapper;
import com.platform.qujia.enums.WxTemplateEnum;
import com.platform.qujia.param.request.CustomMessages;
import com.platform.qujia.pojo.CustomerLabel;
import com.platform.qujia.pojo.LabelRule;
import com.platform.qujia.pojo.dto.LabelRuleDto;
import com.platform.qujia.service.LabelService;
import com.platform.qujia.utils.ResultData;
import com.platform.qujia.utils.weixinapp.WxPushUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("labelService")
public class LabelServiceImpl implements LabelService {
    @Resource
    private LabelMapper labelMapper;
    @Autowired
    private WxPushUtil wxPushUtil;

    //获取标签优惠规则
    @Override
    public List<LabelRule> getLabelRuleList(LabelRule labelRule) {
        return labelMapper.getLabelRuleList(labelRule);
    }

    //新增标签用户
    @Override
    public void insertCustomerLabel(CustomerLabel customerLabel) {
        labelMapper.insertCustomerLabel(customerLabel);
    }

    //更新用户新标签组
    @Override
    public void updateCustomerLabel(CustomerLabel customerLabel) {
        labelMapper.updateCustomerLabel(customerLabel);
    }

    //获取标签用户信息
    @Override
    public CustomerLabel getCustomerLabel(CustomerLabel customerLabel) {
        return labelMapper.getCustomerLabel(customerLabel);
    }

    @Override
    public ResultData<String> sendMessageToUser(CustomMessages customMessages) {
        log.info("sendMessageToUser:{}", customMessages);
        List<String> openIdList = customMessages.getOpenIdList();
        if (CollectionUtils.isNotEmpty(openIdList)) {
            for (String openId : openIdList) {
                Map<String, String> templateParams = new HashMap<>();
                templateParams.put("openid", openId);
                templateParams.put("enterpriseName", customMessages.getEnterpriseName());
                templateParams.put("title", customMessages.getTitle());
                templateParams.put("messages", customMessages.getMessage());
                log.info("自定义消息推送-微信模板参数：{}", templateParams);
                wxPushUtil.sendTemplateMsg(customMessages.getEnterpriseId(), templateParams, WxTemplateEnum.CUSTOM_MESSAGES);
            }
        }
        return ResultData.success();
    }

    @Override
    public int updateIsPush(LabelRuleDto labelRuleDto) {
        return labelMapper.updateIsPush(labelRuleDto);
    }

    @Override
    public LabelRule queryLabelRuleById(Long LabelId) {
        return labelMapper.queryLabelRuleById(LabelId);
    }
}
